/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from '@ohos.file.fs';
import stream from '@ohos.util.stream';
import socket from "@ohos.net.socket";
import business_error from '@ohos.base';
// import { GrpcUri } from './uri-parser';
import url from '@ohos.url';
// import { Message, Reader } from '@ohos/protobufjs';
// import { Metadata } from './metadata';
// import { StatusObject } from './';
import { BufferClass,Buffer } from './buffer';
import { Settings } from './interface/Settings';


export interface incomingHttpHeaders extends Http1IncomingHttpHeaders {
  ":path"?: string | undefined;
  ":method"?: string | undefined;
  ":authority"?: string | undefined;
  ":scheme"?: string | undefined;
}

interface Dict<T> {
  [key: string]: T | undefined;
}

interface Http1IncomingHttpHeaders extends Dict<string | string[]> {
  accept?: string | undefined;
  "accept-language"?: string | undefined;
  "accept-patch"?: string | undefined;
  "accept-ranges"?: string | undefined;
  "access-control-allow-credentials"?: string | undefined;
  "access-control-allow-headers"?: string | undefined;
  "access-control-allow-methods"?: string | undefined;
  "access-control-allow-origin"?: string | undefined;
  "access-control-expose-headers"?: string | undefined;
  "access-control-max-age"?: string | undefined;
  "access-control-request-headers"?: string | undefined;
  "access-control-request-method"?: string | undefined;
  age?: string | undefined;
  allow?: string | undefined;
  "alt-svc"?: string | undefined;
  authorization?: string | undefined;
  "cache-control"?: string | undefined;
  connection?: string | undefined;
  "content-disposition"?: string | undefined;
  "content-encoding"?: string | undefined;
  "content-language"?: string | undefined;
  "content-length"?: string | undefined;
  "content-location"?: string | undefined;
  "content-range"?: string | undefined;
  "content-type"?: string | undefined;
  cookie?: string | undefined;
  date?: string | undefined;
  etag?: string | undefined;
  expect?: string | undefined;
  expires?: string | undefined;
  forwarded?: string | undefined;
  from?: string | undefined;
  host?: string | undefined;
  "if-match"?: string | undefined;
  "if-modified-since"?: string | undefined;
  "if-none-match"?: string | undefined;
  "if-unmodified-since"?: string | undefined;
  "last-modified"?: string | undefined;
  location?: string | undefined;
  origin?: string | undefined;
  pragma?: string | undefined;
  "proxy-authenticate"?: string | undefined;
  "proxy-authorization"?: string | undefined;
  "public-key-pins"?: string | undefined;
  range?: string | undefined;
  referer?: string | undefined;
  "retry-after"?: string | undefined;
  "sec-websocket-accept"?: string | undefined;
  "sec-websocket-extensions"?: string | undefined;
  "sec-websocket-key"?: string | undefined;
  "sec-websocket-protocol"?: string | undefined;
  "sec-websocket-version"?: string | undefined;
  "set-cookie"?: string[] | undefined;
  "strict-transport-security"?: string | undefined;
  tk?: string | undefined;
  trailer?: string | undefined;
  "transfer-encoding"?: string | undefined;
  upgrade?: string | undefined;
  "user-agent"?: string | undefined;
  vary?: string | undefined;
  via?: string | undefined;
  warning?: string | undefined;
  "www-authenticate"?: string | undefined;
}

export interface serverHttp2Stream extends Http2Stream2 {
  readonly headersSent: boolean;
  readonly pushAllowed: boolean;
  additionalHeaders(headers: outgoingHttpHeaders): void;
  pushStream(
    headers: outgoingHttpHeaders,
    callback?: (err: Error | null, pushStream: serverHttp2Stream, headers: outgoingHttpHeaders) => void,
  ): void;
  pushStream(
    headers: outgoingHttpHeaders,
    options?: StreamPriorityOptions,
    callback?: (err: Error | null, pushStream: serverHttp2Stream, headers: outgoingHttpHeaders) => void,
  ): void;
  respond(headers?: outgoingHttpHeaders, options?: ServerStreamResponseOptions): void;
  respondWithFD(
    fd: number,
    headers?: outgoingHttpHeaders,
    options?: ServerStreamFileResponseOptions,
  ): void;
  respondWithFile(
    path: string,
    headers?: outgoingHttpHeaders,
    options?: ServerStreamFileResponseOptionsWithError,
  ): void;
}

export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions {
  onError?(err: ErrnoException): void;
}

export interface ErrnoException extends Error {
  errno?: number | undefined;
  code?: string | undefined;
  path?: string | undefined;
  syscall?: string | undefined;
}

export interface Error {
  name: string;
  message: string;
  stack?: string;
}

export interface StreamPriorityOptions {
  exclusive?: boolean | undefined;
  parent?: number | undefined;
  weight?: number | undefined;
  silent?: boolean | undefined;
}

export interface ServerStreamResponseOptions {
  endStream?: boolean | undefined;
  waitForTrailers?: boolean | undefined;
}

export interface ServerStreamFileResponseOptions {
  statCheck?(stats: fs.Stat, headers: outgoingHttpHeaders, statOptions: StatOptions): void | boolean;
  waitForTrailers?: boolean | undefined;
  offset?: number | undefined;
  length?: number | undefined;
}

export interface StatOptions {
  offset: number;
  length: number;
}

type OutgoingHttpHeader = number | string | string[];

export interface outgoingHttpHeaders extends Dict<OutgoingHttpHeader> {
  accept?: string | string[] | undefined;
  "accept-charset"?: string | string[] | undefined;
  "accept-encoding"?: string | string[] | undefined;
  "accept-language"?: string | string[] | undefined;
  "accept-ranges"?: string | undefined;
  "access-control-allow-credentials"?: string | undefined;
  "access-control-allow-headers"?: string | undefined;
  "access-control-allow-methods"?: string | undefined;
  "access-control-allow-origin"?: string | undefined;
  "access-control-expose-headers"?: string | undefined;
  "access-control-max-age"?: string | undefined;
  "access-control-request-headers"?: string | undefined;
  "access-control-request-method"?: string | undefined;
  age?: string | undefined;
  allow?: string | undefined;
  authorization?: string | undefined;
  "cache-control"?: string | undefined;
  "cdn-cache-control"?: string | undefined;
  connection?: string | string[] | undefined;
  "content-disposition"?: string | undefined;
  "content-encoding"?: string | undefined;
  "content-language"?: string | undefined;
  "content-length"?: string | number | undefined;
  "content-location"?: string | undefined;
  "content-range"?: string | undefined;
  "content-security-policy"?: string | undefined;
  "content-security-policy-report-only"?: string | undefined;
  cookie?: string | string[] | undefined;
  dav?: string | string[] | undefined;
  dnt?: string | undefined;
  date?: string | undefined;
  etag?: string | undefined;
  expect?: string | undefined;
  expires?: string | undefined;
  forwarded?: string | undefined;
  from?: string | undefined;
  host?: string | undefined;
  "if-match"?: string | undefined;
  "if-modified-since"?: string | undefined;
  "if-none-match"?: string | undefined;
  "if-range"?: string | undefined;
  "if-unmodified-since"?: string | undefined;
  "last-modified"?: string | undefined;
  link?: string | string[] | undefined;
  location?: string | undefined;
  "max-forwards"?: string | undefined;
  origin?: string | undefined;
  prgama?: string | string[] | undefined;
  "proxy-authenticate"?: string | string[] | undefined;
  "proxy-authorization"?: string | undefined;
  "public-key-pins"?: string | undefined;
  "public-key-pins-report-only"?: string | undefined;
  range?: string | undefined;
  referer?: string | undefined;
  "referrer-policy"?: string | undefined;
  refresh?: string | undefined;
  "retry-after"?: string | undefined;
  "sec-websocket-accept"?: string | undefined;
  "sec-websocket-extensions"?: string | string[] | undefined;
  "sec-websocket-key"?: string | undefined;
  "sec-websocket-protocol"?: string | string[] | undefined;
  "sec-websocket-version"?: string | undefined;
  server?: string | undefined;
  "set-cookie"?: string | string[] | undefined;
  "strict-transport-security"?: string | undefined;
  te?: string | undefined;
  trailer?: string | undefined;
  "transfer-encoding"?: string | undefined;
  "user-agent"?: string | undefined;
  upgrade?: string | undefined;
  "upgrade-insecure-requests"?: string | undefined;
  vary?: string | undefined;
  via?: string | string[] | undefined;
  warning?: string | undefined;
  "www-authenticate"?: string | string[] | undefined;
  "x-content-type-options"?: string | undefined;
  "x-dns-prefetch-control"?: string | undefined;
  "x-frame-options"?: string | undefined;
  "x-xss-protection"?: string | undefined;
}

export interface Http2Stream2 extends stream.Duplex {
  readonly aborted: boolean;
  readonly bufferSize: number;
  readonly closed: boolean;
  readonly destroyed: boolean;
  readonly endAfterHeaders: boolean;
  readonly id?: number | undefined;
  readonly pending: boolean;
  readonly rstCode: number;
  readonly sentHeaders: outgoingHttpHeaders;
  readonly sentInfoHeaders?: outgoingHttpHeaders[] | undefined;
  readonly sentTrailers?: outgoingHttpHeaders | undefined;
  readonly session:  http2Session | undefined;
  readonly state: StreamState;
  close(code?: number, callback?: () => void): void;
  priority(options: StreamPriorityOptions): void;
  setTimeout(msecs: number, callback?: () => void): void;
  sendTrailers(headers: outgoingHttpHeaders): void;
  addListener(event: "aborted", listener: () => void): this;
  addListener(event: "close", listener: () => void): this;
  addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
  addListener(event: "drain", listener: () => void): this;
  addListener(event: "end", listener: () => void): this;
  addListener(event: "error", listener: (err: Error) => void): this;
  addListener(event: "finish", listener: () => void): this;
  addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
  addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
  addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
  addListener(event: "streamClosed", listener: (code: number) => void): this;
  addListener(event: "timeout", listener: () => void): this;
  addListener(event: "trailers", listener: (trailers: incomingHttpHeaders, flags: number) => void): this;
  addListener(event: "wantTrailers", listener: () => void): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(event: "aborted"): boolean;
  emit(event: "close"): boolean;
  emit(event: "data", chunk: Buffer | string): boolean;
  emit(event: "drain"): boolean;
  emit(event: "end"): boolean;
  emit(event: "error", err: Error): boolean;
  emit(event: "finish"): boolean;
  emit(event: "frameError", frameType: number, errorCode: number): boolean;
  emit(event: "pipe", src: stream.Readable): boolean;
  emit(event: "unpipe", src: stream.Readable): boolean;
  emit(event: "streamClosed", code: number): boolean;
  emit(event: "timeout"): boolean;
  emit(event: "trailers", trailers: incomingHttpHeaders, flags: number): boolean;
  emit(event: "wantTrailers"): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(event: "aborted", listener: () => void): this;
  on(event: "close", listener: () => void): this;
  on(event: "data", listener: (chunk: Buffer | string) => void): this;
  on(event: "drain", listener: () => void): this;
  on(event: "end", listener: () => void): this;
  on(event: "error", listener: (err: Error) => void): this;
  on(event: "finish", listener: () => void): this;
  on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
  on(event: "pipe", listener: (src: stream.Readable) => void): this;
  on(event: "unpipe", listener: (src: stream.Readable) => void): this;
  on(event: "streamClosed", listener: (code: number) => void): this;
  on(event: "timeout", listener: () => void): this;
  on(event: "trailers", listener: (trailers: incomingHttpHeaders, flags: number) => void): this;
  on(event: "wantTrailers", listener: () => void): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(event: "aborted", listener: () => void): this;
  once(event: "close", listener: () => void): this;
  once(event: "data", listener: (chunk: Buffer | string) => void): this;
  once(event: "drain", listener: () => void): this;
  once(event: "end", listener: () => void): this;
  once(event: "error", listener: (err: Error) => void): this;
  once(event: "finish", listener: () => void): this;
  once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
  once(event: "pipe", listener: (src: stream.Readable) => void): this;
  once(event: "unpipe", listener: (src: stream.Readable) => void): this;
  once(event: "streamClosed", listener: (code: number) => void): this;
  once(event: "timeout", listener: () => void): this;
  once(event: "trailers", listener: (trailers: incomingHttpHeaders, flags: number) => void): this;
  once(event: "wantTrailers", listener: () => void): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(event: "aborted", listener: () => void): this;
  prependListener(event: "close", listener: () => void): this;
  prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
  prependListener(event: "drain", listener: () => void): this;
  prependListener(event: "end", listener: () => void): this;
  prependListener(event: "error", listener: (err: Error) => void): this;
  prependListener(event: "finish", listener: () => void): this;
  prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
  prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
  prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
  prependListener(event: "streamClosed", listener: (code: number) => void): this;
  prependListener(event: "timeout", listener: () => void): this;
  prependListener(event: "trailers", listener: (trailers: incomingHttpHeaders, flags: number) => void): this;
  prependListener(event: "wantTrailers", listener: () => void): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(event: "aborted", listener: () => void): this;
  prependOnceListener(event: "close", listener: () => void): this;
  prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
  prependOnceListener(event: "drain", listener: () => void): this;
  prependOnceListener(event: "end", listener: () => void): this;
  prependOnceListener(event: "error", listener: (err: Error) => void): this;
  prependOnceListener(event: "finish", listener: () => void): this;
  prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
  prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
  prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
  prependOnceListener(event: "streamClosed", listener: (code: number) => void): this;
  prependOnceListener(event: "timeout", listener: () => void): this;
  prependOnceListener(event: "trailers", listener: (trailers: incomingHttpHeaders, flags: number) => void): this;
  prependOnceListener(event: "wantTrailers", listener: () => void): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

export interface StreamState {
  localWindowSize?: number | undefined;
  state?: number | undefined;
  localClose?: number | undefined;
  remoteClose?: number | undefined;
  sumDependencyWeight?: number | undefined;
  weight?: number | undefined;
}

export interface SessionState {
  effectiveLocalWindowSize?: number | undefined;
  effectiveRecvDataLength?: number | undefined;
  nextStreamID?: number | undefined;
  localWindowSize?: number | undefined;
  lastProcStreamID?: number | undefined;
  remoteWindowSize?: number | undefined;
  outboundQueueSize?: number | undefined;
  deflateDynamicTableSize?: number | undefined;
  inflateDynamicTableSize?: number | undefined;
}

type TypedArray =
| Uint8Array
  | Uint8ClampedArray
  | Uint16Array
  | Uint32Array
  | Int8Array
  | Int16Array
  | Int32Array
  | BigUint64Array
  | BigInt64Array
  | Float32Array
  | Float64Array;

type ArrayBufferView = TypedArray | DataView;

export interface http2Session {
  readonly alpnProtocol?: string | undefined;
  readonly closed: boolean;
  readonly connecting: boolean;
  readonly destroyed: boolean;
  readonly encrypted?: boolean | undefined;
  readonly localSettings: Settings;
  readonly originSet?: string[] | undefined;
  readonly pendingSettingsAck: boolean;
  readonly remoteSettings: Settings;
  readonly socket: socket.TLSSocket ;
  readonly state: SessionState;
  readonly type: number;
  close(callback?: () => void): void;
  destroy(error?: Error, code?: number): void;
  goaway(code?: number, lastStreamID?: number, opaqueData?: ArrayBufferView): void;
  ping(callback: (err: Error | null, duration: number, payload: BufferClass) => void): boolean;
  // ping(payload: ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean;
  ref(): void;
  setLocalWindowSize(windowSize: number): void;
  setTimeout(msecs: number, callback?: () => void): void;
  settings(
    settings: Settings,
    callback?: (err: Error | null, settings: Settings, duration: number) => void,
  ): void;
  unref(): void;
  addListener(event: "close", listener: () => void): this;
  addListener(event: "error", listener: (err: Error) => void): this;
  addListener(
    event: "frameError",
    listener: (frameType: number, errorCode: number, streamID: number) => void,
  ): this;
  addListener(
    event: "goaway",
    listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
  ): this;
  addListener(event: "localSettings", listener: (settings: Settings) => void): this;
  addListener(event: "ping", listener: () => void): this;
  addListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
  addListener(event: "timeout", listener: () => void): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(event: "close"): boolean;
  emit(event: "error", err: Error): boolean;
  emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean;
  emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean;
  emit(event: "localSettings", settings: Settings): boolean;
  emit(event: "ping"): boolean;
  emit(event: "remoteSettings", settings: Settings): boolean;
  emit(event: "timeout"): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(event: "close", listener: () => void): this;
  on(event: "error", listener: (err: Error) => void): this;
  on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
  on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this;
  on(event: "localSettings", listener: (settings: Settings) => void): this;
  on(event: "ping", listener: () => void): this;
  on(event: "remoteSettings", listener: (settings: Settings) => void): this;
  on(event: "timeout", listener: () => void): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(event: "close", listener: () => void): this;
  once(event: "error", listener: (err: Error) => void): this;
  once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
  once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this;
  once(event: "localSettings", listener: (settings: Settings) => void): this;
  once(event: "ping", listener: () => void): this;
  once(event: "remoteSettings", listener: (settings: Settings) => void): this;
  once(event: "timeout", listener: () => void): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(event: "close", listener: () => void): this;
  prependListener(event: "error", listener: (err: Error) => void): this;
  prependListener(
    event: "frameError",
    listener: (frameType: number, errorCode: number, streamID: number) => void,
  ): this;
  prependListener(
    event: "goaway",
    listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
  ): this;
  prependListener(event: "localSettings", listener: (settings: Settings) => void): this;
  prependListener(event: "ping", listener: () => void): this;
  prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
  prependListener(event: "timeout", listener: () => void): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(event: "close", listener: () => void): this;
  prependOnceListener(event: "error", listener: (err: Error) => void): this;
  prependOnceListener(
    event: "frameError",
    listener: (frameType: number, errorCode: number, streamID: number) => void,
  ): this;
  prependOnceListener(
    event: "goaway",
    listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
  ): this;
  prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this;
  prependOnceListener(event: "ping", listener: () => void): this;
  prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
  prependOnceListener(event: "timeout", listener: () => void): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

interface TcpSubchannelAddress {
  port: number;
  host: string;
}

interface IpcSubchannelAddress {
  path: string;
}

interface KeyObject {
  pem: string | Buffer;
  passphrase?: string | undefined;
}

interface PxfObject {
  buf: string | Buffer;
  passphrase?: string | undefined;
}

export interface SecureContext {
  context: any;
}

type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";

interface LookupOptions {
  family?: number | "IPv4" | "IPv6" | undefined;
  hints?: number | undefined;
  all?: boolean | undefined;
  order?: "ipv4first" | "ipv6first" | "verbatim" | undefined;
  verbatim?: boolean | undefined;
}

interface LookupAddress {
  address: string;
  family: number;
}

type LookupFunction = (
  hostname: string,
  options: LookupOptions,
  callback: (err: business_error.BusinessError | null, address: string | LookupAddress[], family?: number) => void,
) => void;

export interface SecureContextOptions {
  ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;
  ca?: string | Buffer | Array<string | Buffer> | undefined;
  cert?: string | Buffer | Array<string | Buffer> | undefined;
  sigalgs?: string | undefined;
  ciphers?: string | undefined;
  clientCertEngine?: string | undefined;
  crl?: string | Buffer | Array<string | Buffer> | undefined;
  dhparam?: string | Buffer | undefined;
  ecdhCurve?: string | undefined;
  honorCipherOrder?: boolean | undefined;
  key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;
  privateKeyEngine?: string | undefined;
  privateKeyIdentifier?: string | undefined;
  maxVersion?: SecureVersion | undefined;
  minVersion?: SecureVersion | undefined;
  passphrase?: string | undefined;
  pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
  secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
  secureProtocol?: string | undefined;
  sessionIdContext?: string | undefined;
  ticketKeys?: Buffer | undefined;
  sessionTimeout?: number | undefined;
}

interface CommonConnectionOptions {
  secureContext?: SecureContext | undefined;
  enableTrace?: boolean | undefined;
  requestCert?: boolean | undefined;
  ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined;
  SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined;
  rejectUnauthorized?: boolean | undefined;
}

export interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {
  host?: string | undefined;
  port?: number | undefined;
  path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
  socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket
  checkServerIdentity?: Error | undefined | any;
  servername?: string | undefined; // SNI TLS Extension
  session?: Buffer | undefined;
  minDHSize?: number | undefined;
  lookup?: LookupFunction | undefined;
  timeout?: number | undefined;
}

export interface secureClientSessionOptions extends ClientSessionOptions, CommonConnectionOptions {
  servername?: string;
  checkServerIdentity?: any;
}

export interface ClientSessionOptions extends SessionOptions {
  maxReservedRemoteStreams?: number | undefined;
  createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex | Socket) | undefined ;
  protocol?: "http:" | "https:" | undefined;
  servername?: string;
  reqId?:string;
  event?:string;
  callback?:Function;
}

interface SessionOptions {
  maxDeflateDynamicTableSize?: number | undefined;
  maxSessionMemory?: number | undefined;
  maxHeaderListPairs?: number | undefined;
  maxOutstandingPings?: number | undefined;
  maxSendHeaderBlockLength?: number | undefined;
  paddingStrategy?: number | undefined;
  peerMaxConcurrentStreams?: number | undefined;
  settings?: Settings | undefined;
  remoteCustomSettings?: number[] | undefined;
  unknownProtocolTimeout?: number | undefined;
  selectPadding?(frameLen: number, maxFrameLen: number): number;
}

export interface PeerCertificate {
  ca: boolean;
  raw: Buffer;
  subject: Certificate;
  issuer: Certificate;
  valid_from: string;
  valid_to: string;
  serialNumber: string;
  fingerprint: string;
  fingerprint256: string;
  fingerprint512: string;
  ext_key_usage?: string[];
  subjectaltname?: string;
  infoAccess?: Dict<string[]>;
  bits?: number;
  exponent?: string;
  modulus?: string;
  pubkey?: Buffer;
  asn1Curve?: string;
  nistCurve?: string;
}

interface Certificate {
  /**
   * Country code.
   */
  C: string;
  /**
   * Street.
   */
  ST: string;
  /**
   * Locality.
   */
  L: string;
  /**
   * Organization.
   */
  O: string;
  /**
   * Organizational unit.
   */
  OU: string;
  /**
   * Common name.
   */
  CN: string;
}

export interface http2SecureServer {
  readonly listening: boolean;
  removeListener<K,T>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  setSecureContext(options: SecureContextOptions): unknown;
  once(event: "error", listener: (err: Error) => void): this;
  on(arg0: string, arg1: (arg2:any) => void): unknown;
  emit(event: any): boolean;
  address();
  setTimeout(msecs: number, callback?: () => void)
  listen(port?: any, listeningListener?: () => void): void;
  close(arg1:() => void):void;
}

// export interface serverHttp2Session {
//   state: any;
//   encrypted: any;
//   // socket: any;
//
//   on(arg0: string, arg1: () => void): unknown;
//
//   ping(arg0: (err: globalThis.Error, duration: number, payload: Buffer) => void): unknown;
//
//   goaway(arg0: number, arg1: number, kMaxAge: any): unknown;
//
//   close(): unknown;
//
//   destroy(arg0: number): unknown;
//
//   destroy(): unknown;
//
//   destroyed(): unknown;
//
// }

export interface http2ServerOptions {
  settings: { maxConcurrentStreams: number; };
  maxSessionMemory: number;
}

export interface SecureServerOptions {
  requestCert: any;
  key: any;
  rejectUnauthorized?:any;
  cert:any;
  ca: any;
  ciphers?:string;
}
type DefaultEventMap = [never];
type Listener<K, T, F> = T extends DefaultEventMap ? F : (
                                                         K extends keyof T ? (
                                                                             T[K] extends unknown[] ? (...args: T[K]) => void : never
                                                                             )
                                                           : never
                                                         );
type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
type Listener2<K, T> = Listener<K, T, Function>;

// export interface http2Server extends HTTP2ServerCommon {
//   removeListener<K,T>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
//   listen(port?: any, listeningListener?: () => void): void;
//   setTimeout(msecs: number, callback?: () => void)
//   close(): unknown;
//   address();
//   addListener(event: "sessionError", listener: (err: Error) => void): this;
//   addListener(
//     event: "stream",
//     listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
//   ): this;
//   addListener(event: "timeout", listener: () => void): this;
//   addListener(event: string | symbol, listener: (...args: any[]) => void): this;
//   emit(event: "sessionError", err: Error): boolean;
//   emit(event: "stream", stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number): boolean;
//   emit(event: "timeout"): boolean;
//   emit(event: any): boolean;
//   emit(event: "connection",connection: stream.Duplex): boolean;
//   emit(event: string | symbol, ...args: any[]): boolean;
//   on(event: "sessionError", listener: (err: Error) => void): this;
//   on(
//     event: "stream",
//     listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
//   ): this;
//   on(event: "timeout", listener: () => void): this;
//   on(event: string | symbol, listener: (...args: any[]) => void): this;
//   once(event: "sessionError", listener: (err: Error) => void): this;
//   once(
//     event: "stream",
//     listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
//   ): this;
//   once(event: "timeout", listener: () => void): this;
//   once(event: string | symbol, listener: (...args: any[]) => void): this;
//   prependListener(event: "sessionError", listener: (err: Error) => void): this;
//   prependListener(
//     event: "stream",
//     listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
//   ): this;
//   prependListener(event: "timeout", listener: () => void): this;
//   prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
//   prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
//   prependOnceListener(
//     event: "stream",
//     listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
//   ): this;
//   prependOnceListener(event: "timeout", listener: () => void): this;
//   prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
// }

interface HTTP2ServerCommon {
  setTimeout(msec?: number, callback?: () => void): this;
  /**
   * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.
   * Throws ERR_INVALID_ARG_TYPE for invalid settings argument.
   */
  updateSettings(settings: Settings): void;
}

export interface clientHttp2Stream extends Http2Stream2 {
  addListener(event: "continue", listener: () => {}): this;
  addListener(
    event: "headers",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  addListener(event: "push", listener: (headers: incomingHttpHeaders, flags: number) => void): this;
  addListener(
    event: "response",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(event: "continue"): boolean;
  emit(event: "headers", headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
  emit(event: "push", headers: incomingHttpHeaders, flags: number): boolean;
  emit(event: "response", headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(event: "continue", listener: () => {}): this;
  on(
    event: "headers",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  on(event: "push", listener: (headers: incomingHttpHeaders, flags: number) => void): this;
  on(
    event: "response",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(event: "continue", listener: () => {}): this;
  once(
    event: "headers",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  once(event: "push", listener: (headers: incomingHttpHeaders, flags: number) => void): this;
  once(
    event: "response",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(event: "continue", listener: () => {}): this;
  prependListener(
    event: "headers",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  prependListener(event: "push", listener: (headers: incomingHttpHeaders, flags: number) => void): this;
  prependListener(
    event: "response",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(event: "continue", listener: () => {}): this;
  prependOnceListener(
    event: "headers",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  prependOnceListener(event: "push", listener: (headers: incomingHttpHeaders, flags: number) => void): this;
  prependOnceListener(
    event: "response",
    listener: (headers: incomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
  ): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

export interface IncomingHttpStatusHeader {
  ":status"?: number | undefined;
}

export interface clientHttp2Session extends  http2Session {
  removeAllListeners(): unknown;

  request(headers?: outgoingHttpHeaders, options?: ClientSessionRequestOptions): clientHttp2Stream;
  addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
  addListener(event: "origin", listener: (origins: string[]) => void): this;
  addListener(
    event: "connect",
    listener: (session: clientHttp2Session, socket: socket.TLSSocket) => void,
  ): this;
  addListener(
    event: "stream",
    listener: (
      stream: clientHttp2Stream,
      headers: incomingHttpHeaders & IncomingHttpStatusHeader,
      flags: number,
    ) => void,
  ): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(event: "altsvc", alt: string, origin: string, stream: number): boolean;
  emit(event: "origin", origins: readonly string[]): boolean;
  emit(event: "connect", session: clientHttp2Session, socket: socket.TLSSocket): boolean;
  emit(
    event: "stream",
    stream: clientHttp2Stream,
    headers: incomingHttpHeaders & IncomingHttpStatusHeader,
    flags: number,
  ): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
  on(event: "origin", listener: (origins: string[]) => void): this;
  on(event: "connect", listener: (session: clientHttp2Session, socket: socket.TLSSocket) => void): this;
  on(
    event: "stream",
    listener: (
      stream: clientHttp2Stream,
      headers: incomingHttpHeaders & IncomingHttpStatusHeader,
      flags: number,
    ) => void,
  ): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
  once(event: "origin", listener: (origins: string[]) => void): this;
  once(
    event: "connect",
    listener: (session: clientHttp2Session, socket: socket.TLSSocket) => void,
  ): this;
  once(
    event: "stream",
    listener: (
      stream: clientHttp2Stream,
      headers: incomingHttpHeaders & IncomingHttpStatusHeader,
      flags: number,
    ) => void,
  ): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
  prependListener(event: "origin", listener: (origins: string[]) => void): this;
  prependListener(
    event: "connect",
    listener: (session: clientHttp2Session, socket: socket.TLSSocket) => void,
  ): this;
  prependListener(
    event: "stream",
    listener: (
      stream: clientHttp2Stream,
      headers: incomingHttpHeaders & IncomingHttpStatusHeader,
      flags: number,
    ) => void,
  ): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
  prependOnceListener(event: "origin", listener: (origins: string[]) => void): this;
  prependOnceListener(
    event: "connect",
    listener: (session: clientHttp2Session, socket: socket.TLSSocket) => void,
  ): this;
  prependOnceListener(
    event: "stream",
    listener: (
      stream: clientHttp2Stream,
      headers: incomingHttpHeaders & IncomingHttpStatusHeader,
      flags: number,
    ) => void,
  ): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

export interface ClientSessionRequestOptions {
  endStream?: boolean | undefined;
  exclusive?: boolean | undefined;
  parent?: number | undefined;
  weight?: number | undefined;
  waitForTrailers?: boolean | undefined;
  signal?: AbortSignal | undefined;
}

var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
  : {
      prototype: AbortSignal;
      new(): AbortSignal;
      abort(reason?: any): AbortSignal;
      timeout(milliseconds: number): AbortSignal;
      any(signals: AbortSignal[]): AbortSignal;
    };

interface AbortSignal extends EventTarget {
  /**
   * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
   */
  readonly aborted: boolean;
  readonly reason: any;
  onabort: null | ((this: AbortSignal, event: Event) => any);
  throwIfAborted(): void;
}

interface EventTarget extends __EventTarget {}
var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T
  : {
      prototype: __EventTarget;
      new(): __EventTarget;
    };

type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {}
  : {
      /**
       * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
       *
       * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
       *
       * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
       * Specifically, the `capture` option is used as part of the key when registering a `listener`.
       * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
       */
      addEventListener(
        type: string,
        listener: EventListener | EventListenerObject,
        options?: AddEventListenerOptions | boolean,
      ): void;
      /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
      dispatchEvent(event: Event): boolean;
      /** Removes the event listener in target's event listener list with the same type, callback, and options. */
      removeEventListener(
        type: string,
        listener: EventListener | EventListenerObject,
        options?: EventListenerOptions | boolean,
      ): void;
    };

interface EventListener {
  (evt: Event): void;
}

interface EventListenerObject {
  handleEvent(object: Event): void;
}

interface Event extends __Event {}
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
  : {
      prototype: __Event;
      new(type: string, eventInitDict?: EventInit): __Event;
    };

type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {}
  : {
      /** This is not used in Node.js and is provided purely for completeness. */
      readonly bubbles: boolean;
      /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
      cancelBubble: () => void;
      /** True if the event was created with the cancelable option */
      readonly cancelable: boolean;
      /** This is not used in Node.js and is provided purely for completeness. */
      readonly composed: boolean;
      /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
      composedPath(): [EventTarget?];
      /** Alias for event.target. */
      readonly currentTarget: EventTarget | null;
      /** Is true if cancelable is true and event.preventDefault() has been called. */
      readonly defaultPrevented: boolean;
      /** This is not used in Node.js and is provided purely for completeness. */
      readonly eventPhase: 0 | 2;
      /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
      readonly isTrusted: boolean;
      /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
      preventDefault(): void;
      /** This is not used in Node.js and is provided purely for completeness. */
      returnValue: boolean;
      /** Alias for event.target. */
      readonly srcElement: EventTarget | null;
      /** Stops the invocation of event listeners after the current one completes. */
      stopImmediatePropagation(): void;
      /** This is not used in Node.js and is provided purely for completeness. */
      stopPropagation(): void;
      /** The `EventTarget` dispatching the event */
      readonly target: EventTarget | null;
      /** The millisecond timestamp when the Event object was created. */
      readonly timeStamp: number;
      /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
      readonly type: string;
    };

interface EventInit {
  bubbles?: boolean;
  cancelable?: boolean;
  composed?: boolean;
}

interface EventListenerOptions {
  /** Not directly used by Node.js. Added for API completeness. Default: `false`. */
  capture?: boolean;
}

interface AddEventListenerOptions extends EventListenerOptions {
  /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */
  once?: boolean;
  /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */
  passive?: boolean;
  /** The listener will be removed when the given AbortSignal object's `abort()` method is called. */
  signal?: AbortSignal;
}

export interface requestOptions extends ClientRequestArgs {}

interface ClientRequestArgs {
  _defaultAgent?: Agent | undefined;
  agent?: Agent | boolean | undefined;
  auth?: string | null | undefined;
  createConnection?:
    | ((
    options: ClientRequestArgs,
    oncreate: (err: Error | null, socket: stream.Duplex) => void,
  ) => stream.Duplex | null | undefined)
    | undefined;
  defaultPort?: number | string | undefined;
  family?: number | undefined;
  headers?: outgoingHttpHeaders | undefined;
  hints?: LookupOptions["hints"];
  host?: string | null | undefined;
  hostname?: string | null | undefined;
  insecureHTTPParser?: boolean | undefined;
  localAddress?: string | undefined;
  localPort?: number | undefined;
  lookup?: LookupFunction | undefined;
  /**
   * @default 16384
   */
  maxHeaderSize?: number | undefined;
  method?: string | undefined;
  path?: string | null | undefined;
  port?: number | string | null | undefined;
  protocol?: string | null | undefined;
  setHost?: boolean | undefined;
  signal?: AbortSignal | undefined;
  socketPath?: string | undefined;
  timeout?: number | undefined;
  uniqueHeaders?: Array<string | string[]> | undefined;
  joinDuplicateHeaders?: boolean;
}

interface Agent {
  maxFreeSockets: number;
  maxSockets: number;
  maxTotalSockets: number;
  readonly freeSockets: ReadOnlyDict<Socket[]>;
  readonly sockets: ReadOnlyDict<Socket[]>;
  readonly requests: ReadOnlyDict<IncomingMessage[]>;
  constructor(opts?: AgentOptions);
  destroy(): void;
}

interface ReadOnlyDict<T> {
  readonly [key: string]: T | undefined;
}

interface AgentOptions extends Partial<TcpSocketConnectOpts> {
  /**
   * Keep sockets around in a pool to be used by other requests in the future. Default = false
   */
  keepAlive?: boolean | undefined;
  /**
   * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
   * Only relevant if keepAlive is set to true.
   */
  keepAliveMsecs?: number | undefined;
  /**
   * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
   */
  maxSockets?: number | undefined;
  /**
   * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
   */
  maxTotalSockets?: number | undefined;
  /**
   * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
   */
  maxFreeSockets?: number | undefined;
  /**
   * Socket timeout in milliseconds. This will set the timeout after the socket is connected.
   */
  timeout?: number | undefined;
  /**
   * Scheduling strategy to apply when picking the next free socket to use.
   * @default `lifo`
   */
  scheduling?: "fifo" | "lifo" | undefined;
}

interface TcpSocketConnectOpts {
  port: number;
  host?: string | undefined;
  localAddress?: string | undefined;
  localPort?: number | undefined;
  hints?: number | undefined;
  family?: number | undefined;
  lookup?: LookupFunction | undefined;
  noDelay?: boolean | undefined;
  keepAlive?: boolean | undefined;
  keepAliveInitialDelay?: number | undefined;
  autoSelectFamily?: boolean | undefined;
  autoSelectFamilyAttemptTimeout?: number | undefined;
}

interface IncomingMessage extends stream.Readable {
  constructor(socket: Socket);
  aborted: boolean;
  httpVersion: string;
  httpVersionMajor: number;
  httpVersionMinor: number;
  complete: boolean;
  connection: Socket;
  socket: Socket;
  headers: incomingHttpHeaders;
  headersDistinct: Dict<string[]>;
  rawHeaders: string[];
  trailers: Dict<string>;
  trailersDistinct: Dict<string[]>;
  rawTrailers: string[];
  setTimeout(msecs: number, callback?: () => void): this;
  method?: string | undefined;
  url?: string | undefined;
  statusCode?: number | undefined;
  statusMessage?: string | undefined;
  destroy(error?: Error): this;
}

 interface ProtobufTypeDefinition {
  format: string;
  type: object;
  fileDescriptorProtos: Buffer[];
}
export interface MessageTypeDefinition extends ProtobufTypeDefinition {
  format: 'Protocol Buffer 3 DescriptorProto';
}

// export interface MethodDefinition<RequestType, ResponseType, OutputRequestType = RequestType, OutputResponseType = ResponseType> {
//   path: string;
//   requestStream: boolean;
//   responseStream: boolean;
//   requestSerialize: Serialize<RequestType>;
//   responseSerialize: Serialize<ResponseType>;
//   requestDeserialize: Deserialize<OutputRequestType>;
//   responseDeserialize: Deserialize<OutputResponseType>;
//   originalName?: string;
//   requestType: MessageTypeDefinition;
//   responseType: MessageTypeDefinition;
//   options: MethodOptions;
// }

// export interface Serialize<T> {
//   (value: T): Buffer;
// }

// export interface Deserialize<T> {
//   (bytes: Buffer): T;
// }

export interface MethodOptions {
  deprecated: boolean;
  idempotency_level: IdempotencyLevel;
  uninterpreted_option: UninterpretedOption[];
  [k: string]: unknown;
}

export declare enum IdempotencyLevel {
  IDEMPOTENCY_UNKNOWN = "IDEMPOTENCY_UNKNOWN",
  NO_SIDE_EFFECTS = "NO_SIDE_EFFECTS",
  IDEMPOTENT = "IDEMPOTENT"
}

export interface UninterpretedOption {
  name?: NamePart[];
  identifier_value?: string;
  positive_int_value?: number;
  negative_int_value?: number;
  double_value?: number;
  string_value?: string;
  aggregate_value?: string;
}

export interface NamePart {
  name_part: string;
  is_extension: boolean;
}

export interface Console {
  Console: console.ConsoleConstructor;
  /**
   * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
   * writes a message and does not otherwise affect execution. The output always
   * starts with `"Assertion failed"`. If provided, `message` is formatted using
   * [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args).
   *
   * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
   *
   * ```js
   * console.assert(true, 'does nothing');
   *
   * console.assert(false, 'Whoops %s work', 'didn\'t');
   * // Assertion failed: Whoops didn't work
   *
   * console.assert();
   * // Assertion failed
   * ```
   * @since v0.1.101
   * @param value The value tested for being truthy.
   * @param message All arguments besides `value` are used as error message.
   */
  assert(value: any, message?: string, ...optionalParams: any[]): void;
  /**
   * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
   * TTY. When `stdout` is not a TTY, this method does nothing.
   *
   * The specific operation of `console.clear()` can vary across operating systems
   * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the
   * current terminal viewport for the Node.js
   * binary.
   * @since v8.3.0
   */
  clear(): void;
  /**
   * Maintains an internal counter specific to `label` and outputs to `stdout` the
   * number of times `console.count()` has been called with the given `label`.
   *
   * ```js
   * > console.count()
   * default: 1
   * undefined
   * > console.count('default')
   * default: 2
   * undefined
   * > console.count('abc')
   * abc: 1
   * undefined
   * > console.count('xyz')
   * xyz: 1
   * undefined
   * > console.count('abc')
   * abc: 2
   * undefined
   * > console.count()
   * default: 3
   * undefined
   * >
   * ```
   * @since v8.3.0
   * @param [label='default'] The display label for the counter.
   */
  count(label?: string): void;
  /**
   * Resets the internal counter specific to `label`.
   *
   * ```js
   * > console.count('abc');
   * abc: 1
   * undefined
   * > console.countReset('abc');
   * undefined
   * > console.count('abc');
   * abc: 1
   * undefined
   * >
   * ```
   * @since v8.3.0
   * @param [label='default'] The display label for the counter.
   */
  countReset(label?: string): void;
  /**
   * The `console.debug()` function is an alias for {@link log}.
   * @since v8.0.0
   */
  debug(message?: any, ...optionalParams: any[]): void;
  /**
   * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`.
   * This function bypasses any custom `inspect()` function defined on `obj`.
   * @since v0.1.101
   */
  dir(obj: any, options?: InspectOptions): void;
  /**
   * This method calls `console.log()` passing it the arguments received.
   * This method does not produce any XML formatting.
   * @since v8.0.0
   */
  dirxml(...data: any[]): void;
  /**
   * Prints to `stderr` with newline. Multiple arguments can be passed, with the
   * first used as the primary message and all additional used as substitution
   * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
   * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
   *
   * ```js
   * const code = 5;
   * console.error('error #%d', code);
   * // Prints: error #5, to stderr
   * console.error('error', code);
   * // Prints: error 5, to stderr
   * ```
   *
   * If formatting elements (e.g. `%d`) are not found in the first string then
   * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
   * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
   * for more information.
   * @since v0.1.100
   */
  error(message?: any, ...optionalParams: any[]): void;
  /**
   * Increases indentation of subsequent lines by spaces for `groupIndentation` length.
   *
   * If one or more `label`s are provided, those are printed first without the
   * additional indentation.
   * @since v8.5.0
   */
  group(...label: any[]): void;
  /**
   * An alias for {@link group}.
   * @since v8.5.0
   */
  groupCollapsed(...label: any[]): void;
  /**
   * Decreases indentation of subsequent lines by spaces for `groupIndentation` length.
   * @since v8.5.0
   */
  groupEnd(): void;
  /**
   * The `console.info()` function is an alias for {@link log}.
   * @since v0.1.100
   */
  info(message?: any, ...optionalParams: any[]): void;
  /**
   * Prints to `stdout` with newline. Multiple arguments can be passed, with the
   * first used as the primary message and all additional used as substitution
   * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
   * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
   *
   * ```js
   * const count = 5;
   * console.log('count: %d', count);
   * // Prints: count: 5, to stdout
   * console.log('count:', count);
   * // Prints: count: 5, to stdout
   * ```
   *
   * See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
   * @since v0.1.100
   */
  log(message?: any, ...optionalParams: any[]): void;
  /**
   * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just
   * logging the argument if it can't be parsed as tabular.
   *
   * ```js
   * // These can't be parsed as tabular data
   * console.table(Symbol());
   * // Symbol()
   *
   * console.table(undefined);
   * // undefined
   *
   * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
   * // ┌─────────┬─────┬─────┐
   * // │ (index) │  a  │  b  │
   * // ├─────────┼─────┼─────┤
   * // │    0    │  1  │ 'Y' │
   * // │    1    │ 'Z' │  2  │
   * // └─────────┴─────┴─────┘
   *
   * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
   * // ┌─────────┬─────┐
   * // │ (index) │  a  │
   * // ├─────────┼─────┤
   * // │    0    │  1  │
   * // │    1    │ 'Z' │
   * // └─────────┴─────┘
   * ```
   * @since v10.0.0
   * @param properties Alternate properties for constructing the table.
   */
  table(tabularData: any, properties?: readonly string[]): void;
  /**
   * Starts a timer that can be used to compute the duration of an operation. Timers
   * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
   * suitable time units to `stdout`. For example, if the elapsed
   * time is 3869ms, `console.timeEnd()` displays "3.869s".
   * @since v0.1.104
   * @param [label='default']
   */
  time(label?: string): void;
  /**
   * Stops a timer that was previously started by calling {@link time} and
   * prints the result to `stdout`:
   *
   * ```js
   * console.time('bunch-of-stuff');
   * // Do a bunch of stuff.
   * console.timeEnd('bunch-of-stuff');
   * // Prints: bunch-of-stuff: 225.438ms
   * ```
   * @since v0.1.104
   * @param [label='default']
   */
  timeEnd(label?: string): void;
  /**
   * For a timer that was previously started by calling {@link time}, prints
   * the elapsed time and other `data` arguments to `stdout`:
   *
   * ```js
   * console.time('process');
   * const value = expensiveProcess1(); // Returns 42
   * console.timeLog('process', value);
   * // Prints "process: 365.227ms 42".
   * doExpensiveProcess2(value);
   * console.timeEnd('process');
   * ```
   * @since v10.7.0
   * @param [label='default']
   */
  timeLog(label?: string, ...data: any[]): void;
  /**
   * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
   * formatted message and stack trace to the current position in the code.
   *
   * ```js
   * console.trace('Show me');
   * // Prints: (stack trace will vary based on where trace is called)
   * //  Trace: Show me
   * //    at repl:2:9
   * //    at REPLServer.defaultEval (repl.js:248:27)
   * //    at bound (domain.js:287:14)
   * //    at REPLServer.runBound [as eval] (domain.js:300:12)
   * //    at REPLServer.<anonymous> (repl.js:412:12)
   * //    at emitOne (events.js:82:20)
   * //    at REPLServer.emit (events.js:169:7)
   * //    at REPLServer.Interface._onLine (readline.js:210:10)
   * //    at REPLServer.Interface._line (readline.js:549:8)
   * //    at REPLServer.Interface._ttyWrite (readline.js:826:14)
   * ```
   * @since v0.1.104
   */
  trace(message?: any, ...optionalParams: any[]): void;
  /**
   * The `console.warn()` function is an alias for {@link error}.
   * @since v0.1.100
   */
  warn(message?: any, ...optionalParams: any[]): void;
  // --- Inspector mode only ---
  /**
   * This method does not display anything unless used in the inspector. The `console.profile()`
   * method starts a JavaScript CPU profile with an optional label until {@link profileEnd}
   * is called. The profile is then added to the Profile panel of the inspector.
   *
   * ```js
   * console.profile('MyLabel');
   * // Some code
   * console.profileEnd('MyLabel');
   * // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
   * ```
   * @since v8.0.0
   */
  profile(label?: string): void;
  /**
   * This method does not display anything unless used in the inspector. Stops the current
   * JavaScript CPU profiling session if one has been started and prints the report to the
   * Profiles panel of the inspector. See {@link profile} for an example.
   *
   * If this method is called without a label, the most recently started profile is stopped.
   * @since v8.0.0
   */
  profileEnd(label?: string): void;
  /**
   * This method does not display anything unless used in the inspector. The `console.timeStamp()`
   * method adds an event with the label `'label'` to the Timeline panel of the inspector.
   * @since v8.0.0
   */
  timeStamp(label?: string): void;
}

export interface InspectOptions {
  /**
   * If `true`, object's non-enumerable symbols and properties are included in the formatted result.
   * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties).
   * @default false
   */
  showHidden?: boolean | undefined;
  /**
   * Specifies the number of times to recurse while formatting object.
   * This is useful for inspecting large objects.
   * To recurse up to the maximum call stack size pass `Infinity` or `null`.
   * @default 2
   */
  depth?: number | null | undefined;
  /**
   * If `true`, the output is styled with ANSI color codes. Colors are customizable.
   */
  colors?: boolean | undefined;
  /**
   * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked.
   * @default true
   */
  customInspect?: boolean | undefined;
  /**
   * If `true`, `Proxy` inspection includes the target and handler objects.
   * @default false
   */
  showProxy?: boolean | undefined;
  /**
   * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements
   * to include when formatting. Set to `null` or `Infinity` to show all elements.
   * Set to `0` or negative to show no elements.
   * @default 100
   */
  maxArrayLength?: number | null | undefined;
  /**
   * Specifies the maximum number of characters to
   * include when formatting. Set to `null` or `Infinity` to show all elements.
   * Set to `0` or negative to show no characters.
   * @default 10000
   */
  maxStringLength?: number | null | undefined;
  /**
   * The length at which input values are split across multiple lines.
   * Set to `Infinity` to format the input as a single line
   * (in combination with `compact` set to `true` or any number >= `1`).
   * @default 80
   */
  breakLength?: number | undefined;
  /**
   * Setting this to `false` causes each object key
   * to be displayed on a new line. It will also add new lines to text that is
   * longer than `breakLength`. If set to a number, the most `n` inner elements
   * are united on a single line as long as all properties fit into
   * `breakLength`. Short array elements are also grouped together. Note that no
   * text will be reduced below 16 characters, no matter the `breakLength` size.
   * For more information, see the example below.
   * @default true
   */
  compact?: boolean | number | undefined;
  /**
   * If set to `true` or a function, all properties of an object, and `Set` and `Map`
   * entries are sorted in the resulting string.
   * If set to `true` the default sort is used.
   * If set to a function, it is used as a compare function.
   */
  sorted?: boolean | ((a: string, b: string) => number) | undefined;
  /**
   * If set to `true`, getters are going to be
   * inspected as well. If set to `'get'` only getters without setter are going
   * to be inspected. If set to `'set'` only getters having a corresponding
   * setter are going to be inspected. This might cause side effects depending on
   * the getter function.
   * @default false
   */
  getters?: "get" | "set" | boolean | undefined;
  /**
   * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers.
   * @default false
   */
  numericSeparator?: boolean | undefined;
}

namespace console {
  interface ConsoleConstructorOptions {
    /**
     * Ignore errors when writing to the underlying streams.
     * @default true
     */
    ignoreErrors?: boolean | undefined;
    /**
     * Set color support for this `Console` instance. Setting to true enables coloring while inspecting
     * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color
     * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the
     * respective stream. This option can not be used, if `inspectOptions.colors` is set as well.
     * @default auto
     */
    colorMode?: boolean | "auto" | undefined;
    /**
     * Specifies options that are passed along to
     * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options).
     */
    inspectOptions?: InspectOptions | undefined;
    /**
     * Set group indentation.
     * @default 2
     */
    groupIndentation?: number | undefined;
  }
  export interface ConsoleConstructor {
    prototype: Console;
    new(stdout: stream.Writable, stderr?: stream.Writable, ignoreErrors?: boolean): Console;
    new(options: ConsoleConstructorOptions): Console;
  }
}

export interface http2Server<
Http1Request extends IncomingMessage = IncomingMessage ,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends Server, HTTP2ServerCommon {
  addListener(
    event: "checkContinue",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  addListener(
    event: "request",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  addListener(event: "sessionError", listener: (err: Error) => void): this;
  addListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  addListener(event: "timeout", listener: () => void): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(
    event: "checkContinue",
    request: InstanceType<Http2Request>,
    response: InstanceType<Http2Response>,
  ): boolean;
  emit(event: "request", request: InstanceType<Http2Request>, response: InstanceType<Http2Response>): boolean;
  emit(event: "sessionError", err: Error): boolean;
  emit(event: "stream", stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number): boolean;
  emit(event: "timeout"): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(
    event: "checkContinue",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  on(
    event: "request",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  on(event: "sessionError", listener: (err: Error) => void): this;
  on(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  on(event: "timeout", listener: () => void): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(
    event: "checkContinue",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  once(
    event: "request",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  once(event: "sessionError", listener: (err: Error) => void): this;
  once(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  once(event: "timeout", listener: () => void): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(
    event: "checkContinue",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  prependListener(
    event: "request",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  prependListener(event: "sessionError", listener: (err: Error) => void): this;
  prependListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  prependListener(event: "timeout", listener: () => void): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(
    event: "checkContinue",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  prependOnceListener(
    event: "request",
    listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
  ): this;
  prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
  prependOnceListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  prependOnceListener(event: "timeout", listener: () => void): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
  removeListener<K,T>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  listen(port?: any, listeningListener?: () => void): void;
  setTimeout(msecs: number, callback?: () => void)
  close(): unknown;
  address();
}

class OutgoingMessage<Request extends IncomingMessage = IncomingMessage> extends stream.Writable {
  readonly req: Request;
  chunkedEncoding: boolean;
  shouldKeepAlive: boolean;
  useChunkedEncodingByDefault: boolean;
  sendDate: boolean;
  /**
   * @deprecated Use `writableEnded` instead.
   */
  finished: boolean;
  /**
   * Read-only. `true` if the headers were sent, otherwise `false`.
   * @since v0.9.3
   */
  readonly headersSent: boolean;
  /**
   * Alias of `outgoingMessage.socket`.
   * @since v0.3.0
   * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead.
   */
  readonly connection: Socket | null;
  /**
   * Reference to the underlying socket. Usually, users will not want to access
   * this property.
   *
   * After calling `outgoingMessage.end()`, this property will be nulled.
   * @since v0.3.0
   */
  readonly socket: Socket | null;
}

class ServerResponse<Request extends IncomingMessage = IncomingMessage> extends OutgoingMessage<Request> {
  statusCode: number;
  statusMessage: string;
  strictContentLength: boolean;
}

export class Http2ServerRequest extends stream.Readable {
  readonly aborted: boolean;
  readonly authority: string;
  readonly connection: socket.TLSSocket;
  readonly complete: boolean;
  readonly headers: incomingHttpHeaders;
  readonly httpVersion: string;
  readonly httpVersionMinor: number;
  readonly httpVersionMajor: number;
  readonly method: string;
  readonly rawHeaders: string[];
  readonly rawTrailers: string[];
  readonly scheme: string;
  readonly socket: socket.TLSSocket;
  readonly stream: serverHttp2Stream;
}

export class Http2ServerResponse<Request extends Http2ServerRequest = Http2ServerRequest> extends stream.Writable {
  readonly finished: boolean;
  readonly headersSent: boolean;
  readonly req: Request;
}

class Server {
  maxConnections: number;
  connections: number;
  readonly listening: boolean;
}

export interface SecureServerSessionOptions<
Http1Request extends IncomingMessage = IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends ServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response> {}

// export interface ServerOptions<
// Http1Request extends IncomingMessage = IncomingMessage,
// Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
// Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
// Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
// > extends ServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response> {}

export interface secureServerOptions<
Http1Request extends IncomingMessage = IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends SecureServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response> {
  allowHTTP1?: boolean | undefined;
  origins?: string[] | undefined;
  requestCert: any;
  key: any;
  rejectUnauthorized?:any;
  cert:any;
  ca: any;
  ciphers?:string;
}
export interface ServerSessionOptions<
Http1Request extends IncomingMessage = IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends SessionOptions {
  Http1IncomingMessage?: Http1Request | undefined;
  Http1ServerResponse?: Http1Response | undefined;
  Http2ServerRequest?: Http2Request | undefined;
  Http2ServerResponse?: Http2Response | undefined;
}

export interface serverHttp2Session<
Http1Request extends IncomingMessage = IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends  http2Session {
  readonly server:
    | http2Server<Http1Request, Http1Response, Http2Request, Http2Response>
    // | Http2SecureServer<Http1Request, Http1Response, Http2Request, Http2Response>;
  origin(
    ...origins: Array<
    | string
      | url.URL
      | {
      origin: string;
    }
    >
  ): void;
  addListener(
    event: "connect",
    listener: (
      session: serverHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
      socket: socket.TLSSocket,
    ) => void,
  ): this;
  addListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  emit(
    event: "connect",
    session: serverHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
    socket: socket.TLSSocket,
  ): boolean;
  emit(event: "stream", stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number): boolean;
  emit(event: string | symbol, ...args: any[]): boolean;
  on(
    event: "connect",
    listener: (
      session: serverHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
      socket: socket.TLSSocket,
    ) => void,
  ): this;
  on(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  once(
    event: "connect",
    listener: (
      session: serverHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
      socket: socket.TLSSocket,
    ) => void,
  ): this;
  once(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  once(event: string | symbol, listener: (...args: any[]) => void): this;
  prependListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  prependOnceListener(
    event: "stream",
    listener: (stream: serverHttp2Stream, headers: incomingHttpHeaders, flags: number) => void,
  ): this;
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
  state: any;
  encrypted: any;
  // socket: any;

  on(arg0: string, arg1: () => void): unknown;

  // ping(arg0: (err: globalThis.Error, duration: number, payload: Buffer) => void): unknown;

  goaway(arg0: number, arg1: number, kMaxAge: any): unknown;

  close(): unknown;

  destroy(arg0: number): unknown;

  destroy(): unknown;
}

export const apiData = {
  "nested": {
    "google": {
      "nested": {
        "protobuf": {
          "nested": {
            "Api": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "methods": {
                  "rule": "repeated",
                  "type": "Method",
                  "id": 2
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 3
                },
                "version": {
                  "type": "string",
                  "id": 4
                },
                "sourceContext": {
                  "type": "SourceContext",
                  "id": 5
                },
                "mixins": {
                  "rule": "repeated",
                  "type": "Mixin",
                  "id": 6
                },
                "syntax": {
                  "type": "Syntax",
                  "id": 7
                }
              }
            },
            "Method": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "requestTypeUrl": {
                  "type": "string",
                  "id": 2
                },
                "requestStreaming": {
                  "type": "bool",
                  "id": 3
                },
                "responseTypeUrl": {
                  "type": "string",
                  "id": 4
                },
                "responseStreaming": {
                  "type": "bool",
                  "id": 5
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 6
                },
                "syntax": {
                  "type": "Syntax",
                  "id": 7
                }
              }
            },
            "Mixin": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "root": {
                  "type": "string",
                  "id": 2
                }
              }
            },
            "SourceContext": {
              "fields": {
                "fileName": {
                  "type": "string",
                  "id": 1
                }
              }
            },
            "Option": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "value": {
                  "type": "Any",
                  "id": 2
                }
              }
            },
            "Syntax": {
              "values": {
                "SYNTAX_PROTO2": 0,
                "SYNTAX_PROTO3": 1
              }
            }
          }
        }
      }
    }
  }
}
export const descriptorData = {
  "nested": {
    "google": {
      "nested": {
        "protobuf": {
          "nested": {
            "FileDescriptorSet": {
              "fields": {
                "file": {
                  "rule": "repeated",
                  "type": "FileDescriptorProto",
                  "id": 1
                }
              }
            },
            "FileDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "package": {
                  "type": "string",
                  "id": 2
                },
                "dependency": {
                  "rule": "repeated",
                  "type": "string",
                  "id": 3
                },
                "publicDependency": {
                  "rule": "repeated",
                  "type": "int32",
                  "id": 10,
                  "options": {
                    "packed": false
                  }
                },
                "weakDependency": {
                  "rule": "repeated",
                  "type": "int32",
                  "id": 11,
                  "options": {
                    "packed": false
                  }
                },
                "messageType": {
                  "rule": "repeated",
                  "type": "DescriptorProto",
                  "id": 4
                },
                "enumType": {
                  "rule": "repeated",
                  "type": "EnumDescriptorProto",
                  "id": 5
                },
                "service": {
                  "rule": "repeated",
                  "type": "ServiceDescriptorProto",
                  "id": 6
                },
                "extension": {
                  "rule": "repeated",
                  "type": "FieldDescriptorProto",
                  "id": 7
                },
                "options": {
                  "type": "FileOptions",
                  "id": 8
                },
                "sourceCodeInfo": {
                  "type": "SourceCodeInfo",
                  "id": 9
                },
                "syntax": {
                  "type": "string",
                  "id": 12
                }
              }
            },
            "DescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "field": {
                  "rule": "repeated",
                  "type": "FieldDescriptorProto",
                  "id": 2
                },
                "extension": {
                  "rule": "repeated",
                  "type": "FieldDescriptorProto",
                  "id": 6
                },
                "nestedType": {
                  "rule": "repeated",
                  "type": "DescriptorProto",
                  "id": 3
                },
                "enumType": {
                  "rule": "repeated",
                  "type": "EnumDescriptorProto",
                  "id": 4
                },
                "extensionRange": {
                  "rule": "repeated",
                  "type": "ExtensionRange",
                  "id": 5
                },
                "oneofDecl": {
                  "rule": "repeated",
                  "type": "OneofDescriptorProto",
                  "id": 8
                },
                "options": {
                  "type": "MessageOptions",
                  "id": 7
                },
                "reservedRange": {
                  "rule": "repeated",
                  "type": "ReservedRange",
                  "id": 9
                },
                "reservedName": {
                  "rule": "repeated",
                  "type": "string",
                  "id": 10
                }
              },
              "nested": {
                "ExtensionRange": {
                  "fields": {
                    "start": {
                      "type": "int32",
                      "id": 1
                    },
                    "end": {
                      "type": "int32",
                      "id": 2
                    }
                  }
                },
                "ReservedRange": {
                  "fields": {
                    "start": {
                      "type": "int32",
                      "id": 1
                    },
                    "end": {
                      "type": "int32",
                      "id": 2
                    }
                  }
                }
              }
            },
            "FieldDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "number": {
                  "type": "int32",
                  "id": 3
                },
                "label": {
                  "type": "Label",
                  "id": 4
                },
                "type": {
                  "type": "Type",
                  "id": 5
                },
                "typeName": {
                  "type": "string",
                  "id": 6
                },
                "extendee": {
                  "type": "string",
                  "id": 2
                },
                "defaultValue": {
                  "type": "string",
                  "id": 7
                },
                "oneofIndex": {
                  "type": "int32",
                  "id": 9
                },
                "jsonName": {
                  "type": "string",
                  "id": 10
                },
                "options": {
                  "type": "FieldOptions",
                  "id": 8
                }
              },
              "nested": {
                "Type": {
                  "values": {
                    "TYPE_DOUBLE": 1,
                    "TYPE_FLOAT": 2,
                    "TYPE_INT64": 3,
                    "TYPE_UINT64": 4,
                    "TYPE_INT32": 5,
                    "TYPE_FIXED64": 6,
                    "TYPE_FIXED32": 7,
                    "TYPE_BOOL": 8,
                    "TYPE_STRING": 9,
                    "TYPE_GROUP": 10,
                    "TYPE_MESSAGE": 11,
                    "TYPE_BYTES": 12,
                    "TYPE_UINT32": 13,
                    "TYPE_ENUM": 14,
                    "TYPE_SFIXED32": 15,
                    "TYPE_SFIXED64": 16,
                    "TYPE_SINT32": 17,
                    "TYPE_SINT64": 18
                  }
                },
                "Label": {
                  "values": {
                    "LABEL_OPTIONAL": 1,
                    "LABEL_REQUIRED": 2,
                    "LABEL_REPEATED": 3
                  }
                }
              }
            },
            "OneofDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "options": {
                  "type": "OneofOptions",
                  "id": 2
                }
              }
            },
            "EnumDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "value": {
                  "rule": "repeated",
                  "type": "EnumValueDescriptorProto",
                  "id": 2
                },
                "options": {
                  "type": "EnumOptions",
                  "id": 3
                }
              }
            },
            "EnumValueDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "number": {
                  "type": "int32",
                  "id": 2
                },
                "options": {
                  "type": "EnumValueOptions",
                  "id": 3
                }
              }
            },
            "ServiceDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "method": {
                  "rule": "repeated",
                  "type": "MethodDescriptorProto",
                  "id": 2
                },
                "options": {
                  "type": "ServiceOptions",
                  "id": 3
                }
              }
            },
            "MethodDescriptorProto": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "inputType": {
                  "type": "string",
                  "id": 2
                },
                "outputType": {
                  "type": "string",
                  "id": 3
                },
                "options": {
                  "type": "MethodOptions",
                  "id": 4
                },
                "clientStreaming": {
                  "type": "bool",
                  "id": 5
                },
                "serverStreaming": {
                  "type": "bool",
                  "id": 6
                }
              }
            },
            "FileOptions": {
              "fields": {
                "javaPackage": {
                  "type": "string",
                  "id": 1
                },
                "javaOuterClassname": {
                  "type": "string",
                  "id": 8
                },
                "javaMultipleFiles": {
                  "type": "bool",
                  "id": 10
                },
                "javaGenerateEqualsAndHash": {
                  "type": "bool",
                  "id": 20,
                  "options": {
                    "deprecated": true
                  }
                },
                "javaStringCheckUtf8": {
                  "type": "bool",
                  "id": 27
                },
                "optimizeFor": {
                  "type": "OptimizeMode",
                  "id": 9,
                  "options": {
                    "default": "SPEED"
                  }
                },
                "goPackage": {
                  "type": "string",
                  "id": 11
                },
                "ccGenericServices": {
                  "type": "bool",
                  "id": 16
                },
                "javaGenericServices": {
                  "type": "bool",
                  "id": 17
                },
                "pyGenericServices": {
                  "type": "bool",
                  "id": 18
                },
                "deprecated": {
                  "type": "bool",
                  "id": 23
                },
                "ccEnableArenas": {
                  "type": "bool",
                  "id": 31
                },
                "objcClassPrefix": {
                  "type": "string",
                  "id": 36
                },
                "csharpNamespace": {
                  "type": "string",
                  "id": 37
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ],
              "reserved": [
                [
                  38,
                  38
                ]
              ],
              "nested": {
                "OptimizeMode": {
                  "values": {
                    "SPEED": 1,
                    "CODE_SIZE": 2,
                    "LITE_RUNTIME": 3
                  }
                }
              }
            },
            "MessageOptions": {
              "fields": {
                "messageSetWireFormat": {
                  "type": "bool",
                  "id": 1
                },
                "noStandardDescriptorAccessor": {
                  "type": "bool",
                  "id": 2
                },
                "deprecated": {
                  "type": "bool",
                  "id": 3
                },
                "mapEntry": {
                  "type": "bool",
                  "id": 7
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ],
              "reserved": [
                [
                  8,
                  8
                ]
              ]
            },
            "FieldOptions": {
              "fields": {
                "ctype": {
                  "type": "CType",
                  "id": 1,
                  "options": {
                    "default": "STRING"
                  }
                },
                "packed": {
                  "type": "bool",
                  "id": 2
                },
                "jstype": {
                  "type": "JSType",
                  "id": 6,
                  "options": {
                    "default": "JS_NORMAL"
                  }
                },
                "lazy": {
                  "type": "bool",
                  "id": 5
                },
                "deprecated": {
                  "type": "bool",
                  "id": 3
                },
                "weak": {
                  "type": "bool",
                  "id": 10
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ],
              "reserved": [
                [
                  4,
                  4
                ]
              ],
              "nested": {
                "CType": {
                  "values": {
                    "STRING": 0,
                    "CORD": 1,
                    "STRING_PIECE": 2
                  }
                },
                "JSType": {
                  "values": {
                    "JS_NORMAL": 0,
                    "JS_STRING": 1,
                    "JS_NUMBER": 2
                  }
                }
              }
            },
            "OneofOptions": {
              "fields": {
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ]
            },
            "EnumOptions": {
              "fields": {
                "allowAlias": {
                  "type": "bool",
                  "id": 2
                },
                "deprecated": {
                  "type": "bool",
                  "id": 3
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ]
            },
            "EnumValueOptions": {
              "fields": {
                "deprecated": {
                  "type": "bool",
                  "id": 1
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ]
            },
            "ServiceOptions": {
              "fields": {
                "deprecated": {
                  "type": "bool",
                  "id": 33
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ]
            },
            "MethodOptions": {
              "fields": {
                "deprecated": {
                  "type": "bool",
                  "id": 33
                },
                "uninterpretedOption": {
                  "rule": "repeated",
                  "type": "UninterpretedOption",
                  "id": 999
                }
              },
              "extensions": [
                [
                  1000,
                  536870911
                ]
              ]
            },
            "UninterpretedOption": {
              "fields": {
                "name": {
                  "rule": "repeated",
                  "type": "NamePart",
                  "id": 2
                },
                "identifierValue": {
                  "type": "string",
                  "id": 3
                },
                "positiveIntValue": {
                  "type": "uint64",
                  "id": 4
                },
                "negativeIntValue": {
                  "type": "int64",
                  "id": 5
                },
                "doubleValue": {
                  "type": "double",
                  "id": 6
                },
                "stringValue": {
                  "type": "bytes",
                  "id": 7
                },
                "aggregateValue": {
                  "type": "string",
                  "id": 8
                }
              },
              "nested": {
                "NamePart": {
                  "fields": {
                    "namePart": {
                      "rule": "required",
                      "type": "string",
                      "id": 1
                    },
                    "isExtension": {
                      "rule": "required",
                      "type": "bool",
                      "id": 2
                    }
                  }
                }
              }
            },
            "SourceCodeInfo": {
              "fields": {
                "location": {
                  "rule": "repeated",
                  "type": "Location",
                  "id": 1
                }
              },
              "nested": {
                "Location": {
                  "fields": {
                    "path": {
                      "rule": "repeated",
                      "type": "int32",
                      "id": 1
                    },
                    "span": {
                      "rule": "repeated",
                      "type": "int32",
                      "id": 2
                    },
                    "leadingComments": {
                      "type": "string",
                      "id": 3
                    },
                    "trailingComments": {
                      "type": "string",
                      "id": 4
                    },
                    "leadingDetachedComments": {
                      "rule": "repeated",
                      "type": "string",
                      "id": 6
                    }
                  }
                }
              }
            },
            "GeneratedCodeInfo": {
              "fields": {
                "annotation": {
                  "rule": "repeated",
                  "type": "Annotation",
                  "id": 1
                }
              },
              "nested": {
                "Annotation": {
                  "fields": {
                    "path": {
                      "rule": "repeated",
                      "type": "int32",
                      "id": 1
                    },
                    "sourceFile": {
                      "type": "string",
                      "id": 2
                    },
                    "begin": {
                      "type": "int32",
                      "id": 3
                    },
                    "end": {
                      "type": "int32",
                      "id": 4
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
export const source_contextData = {
  "nested": {
    "google": {
      "nested": {
        "protobuf": {
          "nested": {
            "SourceContext": {
              "fields": {
                "fileName": {
                  "type": "string",
                  "id": 1
                }
              }
            }
          }
        }
      }
    }
  }
}
export const typeData = {
  "nested": {
    "google": {
      "nested": {
        "protobuf": {
          "nested": {
            "Type": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "fields": {
                  "rule": "repeated",
                  "type": "Field",
                  "id": 2
                },
                "oneofs": {
                  "rule": "repeated",
                  "type": "string",
                  "id": 3
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 4
                },
                "sourceContext": {
                  "type": "SourceContext",
                  "id": 5
                },
                "syntax": {
                  "type": "Syntax",
                  "id": 6
                }
              }
            },
            "Field": {
              "fields": {
                "kind": {
                  "type": "Kind",
                  "id": 1
                },
                "cardinality": {
                  "type": "Cardinality",
                  "id": 2
                },
                "number": {
                  "type": "int32",
                  "id": 3
                },
                "name": {
                  "type": "string",
                  "id": 4
                },
                "typeUrl": {
                  "type": "string",
                  "id": 6
                },
                "oneofIndex": {
                  "type": "int32",
                  "id": 7
                },
                "packed": {
                  "type": "bool",
                  "id": 8
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 9
                },
                "jsonName": {
                  "type": "string",
                  "id": 10
                },
                "defaultValue": {
                  "type": "string",
                  "id": 11
                }
              },
              "nested": {
                "Kind": {
                  "values": {
                    "TYPE_UNKNOWN": 0,
                    "TYPE_DOUBLE": 1,
                    "TYPE_FLOAT": 2,
                    "TYPE_INT64": 3,
                    "TYPE_UINT64": 4,
                    "TYPE_INT32": 5,
                    "TYPE_FIXED64": 6,
                    "TYPE_FIXED32": 7,
                    "TYPE_BOOL": 8,
                    "TYPE_STRING": 9,
                    "TYPE_GROUP": 10,
                    "TYPE_MESSAGE": 11,
                    "TYPE_BYTES": 12,
                    "TYPE_UINT32": 13,
                    "TYPE_ENUM": 14,
                    "TYPE_SFIXED32": 15,
                    "TYPE_SFIXED64": 16,
                    "TYPE_SINT32": 17,
                    "TYPE_SINT64": 18
                  }
                },
                "Cardinality": {
                  "values": {
                    "CARDINALITY_UNKNOWN": 0,
                    "CARDINALITY_OPTIONAL": 1,
                    "CARDINALITY_REQUIRED": 2,
                    "CARDINALITY_REPEATED": 3
                  }
                }
              }
            },
            "Enum": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "enumvalue": {
                  "rule": "repeated",
                  "type": "EnumValue",
                  "id": 2
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 3
                },
                "sourceContext": {
                  "type": "SourceContext",
                  "id": 4
                },
                "syntax": {
                  "type": "Syntax",
                  "id": 5
                }
              }
            },
            "EnumValue": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "number": {
                  "type": "int32",
                  "id": 2
                },
                "options": {
                  "rule": "repeated",
                  "type": "Option",
                  "id": 3
                }
              }
            },
            "Option": {
              "fields": {
                "name": {
                  "type": "string",
                  "id": 1
                },
                "value": {
                  "type": "Any",
                  "id": 2
                }
              }
            },
            "Syntax": {
              "values": {
                "SYNTAX_PROTO2": 0,
                "SYNTAX_PROTO3": 1
              }
            },
            "Any": {
              "fields": {
                "type_url": {
                  "type": "string",
                  "id": 1
                },
                "value": {
                  "type": "bytes",
                  "id": 2
                }
              }
            },
            "SourceContext": {
              "fields": {
                "fileName": {
                  "type": "string",
                  "id": 1
                }
              }
            }
          }
        }
      }
    }
  }
}

interface Uint8Array {
  readonly BYTES_PER_ELEMENT: number;
  readonly buffer: ArrayBufferLike;
  readonly byteLength: number;
  readonly byteOffset: number;
  copyWithin(target: number, start: number, end?: number): this;
  every(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean;
  fill(value: number, start?: number, end?: number): this;
  filter(predicate: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;
  find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;
  findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;
  forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;
  indexOf(searchElement: number, fromIndex?: number): number;
  join(separator?: string): string;
  lastIndexOf(searchElement: number, fromIndex?: number): number;
  readonly length: number;
  map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;
  reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;
  reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;
  reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;
  reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;
  reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;
  reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;
  reverse(): Uint8Array;
  set(array: ArrayLike<number>, offset?: number): void;
  slice(start?: number, end?: number): Uint8Array;
  some(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean;
  sort(compareFn?: (a: number, b: number) => number): this;
  subarray(begin?: number, end?: number): Uint8Array;
  toLocaleString(): string;
  toString(): string;
  valueOf(): Uint8Array;
  [index: number]: number;
}

interface NodeBuffer extends Uint8Array {
  write(string: string, offset?: number, length?: number, encoding?: string): number;
  toString(encoding?: string, start?: number, end?: number): string;
  toJSON(): { type: 'Buffer', data: any[] };
  equals(otherBuffer: Buffer): boolean;
  copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
  writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
  readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
  readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
  readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
  readUInt8(offset: number, noAssert?: boolean): number;
  readUInt16LE(offset: number, noAssert?: boolean): number;
  readUInt16BE(offset: number, noAssert?: boolean): number;
  readUInt32LE(offset: number, noAssert?: boolean): number;
  readUInt32BE(offset: number, noAssert?: boolean): number;
  readInt8(offset: number, noAssert?: boolean): number;
  readInt16LE(offset: number, noAssert?: boolean): number;
  readInt16BE(offset: number, noAssert?: boolean): number;
  readInt32LE(offset: number, noAssert?: boolean): number;
  readInt32BE(offset: number, noAssert?: boolean): number;
  readFloatLE(offset: number, noAssert?: boolean): number;
  readFloatBE(offset: number, noAssert?: boolean): number;
  readDoubleLE(offset: number, noAssert?: boolean): number;
  readDoubleBE(offset: number, noAssert?: boolean): number;
  swap16(): Buffer;
  swap32(): Buffer;
  swap64(): Buffer;
  writeUInt8(value: number, offset: number, noAssert?: boolean): number;
  writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
  writeInt8(value: number, offset: number, noAssert?: boolean): number;
  writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
  writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
  writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
  writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
  writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
  writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
  writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
  writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
  fill(value: any, offset?: number, end?: number): this;
  indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
  lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
  entries(): IterableIterator<[number, number]>;
  includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
  keys(): IterableIterator<number>;
  values(): IterableIterator<number>;
}

export interface EventEmitter<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {}
type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
type Args<K, T> = T extends DefaultEventMap ? AnyRest : (K extends keyof T ? T[K] : never);
type AnyRest = [...args: any[]];
type Key2<K, T> = T extends DefaultEventMap ? string | symbol : K & keyof T;
namespace NodeJS {
  export interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
    [EventEmitter1.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
    on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
    once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
    removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
    setMaxListeners(n: number): this;
    getMaxListeners(): number;
    emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
    prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
    prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;

  }
}
export class EventEmitter1<T extends EventMap<T> = DefaultEventMap> {
  static readonly errorMonitor: unique symbol;
  static readonly captureRejectionSymbol: unique symbol;
  static captureRejections: boolean;
  static defaultMaxListeners: number;
  off<K>(eventName: string | symbol, listener: (...args: any[]) => void): this {
    throw new Error('Method not implemented.');
  }

  // addListener(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // addListener(event: 'status', listener: (arg1: StatusObject) => void): this;

  addListener<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  addListener(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  // emit(event: 'metadata', arg1: Metadata): boolean;

  // emit(event: 'status', arg1: StatusObject): boolean;

  emit<K>(eventName: string | symbol, ...args: any[]): boolean;

  emit(event: unknown, arg1?: unknown, ...rest: unknown[]): boolean {
    throw new Error('Method not implemented.');
  }

  // on(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // on(event: 'status', listener: (arg1: StatusObject) => void): this;

  on<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  on(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  // once(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // once(event: 'status', listener: (arg1: StatusObject) => void): this;

  once<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  once(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  // prependListener(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // prependListener(event: 'status', listener: (arg1: StatusObject) => void): this;

  prependListener<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  prependListener(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  // prependOnceListener(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // prependOnceListener(event: 'status', listener: (arg1: StatusObject) => void): this;

  prependOnceListener<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  prependOnceListener(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  // removeListener(event: 'metadata', listener: (arg1: Metadata) => void): this;

  // removeListener(event: 'status', listener: (arg1: StatusObject) => void): this;

  removeListener<K>(eventName: string | symbol, listener: (...args: any[]) => void): this;

  removeListener(event: unknown, listener: unknown): this {
    throw new Error('Method not implemented.');
  }

  removeAllListeners(eventName?: string | symbol): this {
    throw new Error('Method not implemented.');
  }

  setMaxListeners(n: number): this {
    throw new Error('Method not implemented.');
  }

  getMaxListeners(): number {
    throw new Error('Method not implemented.');
  }

  listeners<K>(eventName: string | symbol): Function[] {
    throw new Error('Method not implemented.');
  }

  rawListeners<K>(eventName: string | symbol): Function[] {
    throw new Error('Method not implemented.');
  }

  listenerCount<K>(eventName: string | symbol, listener?: Function): number {
    throw new Error('Method not implemented.');
  }

  eventNames(): (string | symbol)[] {
    throw new Error('Method not implemented.');
  }

  read(size?: number): any;

  read(size?: unknown): any {
    throw new Error('Method not implemented.');
  }
}

export interface Socket {
  // constructor(options?: SocketConstructorOpts);
  destroySoon(): void;
  write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
  connect(port: number, host: string, connectionListener?: () => void): this;
  connect(port: number, connectionListener?: () => void): this;
  connect(path: string, connectionListener?: () => void): this;
  pause(): this;
  resetAndDestroy(): this;
  resume(): this;
  setTimeout(timeout: number, callback?: () => void): this;
  setNoDelay(noDelay?: boolean): this;
  setKeepAlive(enable?: boolean, initialDelay?: number): this;
  unref(): this;
  ref(): this;
  readonly autoSelectFamilyAttemptedAddresses: string[];
  readonly bufferSize: number;
  readonly bytesRead: number;
  readonly bytesWritten: number;
  readonly connecting: boolean;
  readonly pending: boolean;
  readonly destroyed: boolean;
  readonly localAddress?: string;
  readonly localPort?: number;
  readonly localFamily?: string;
  readonly remoteAddress?: string | undefined;
  readonly remoteFamily?: string | undefined;
  readonly remotePort?: number | undefined;
  readonly timeout?: number | undefined;
  end(callback?: () => void): this;
  end(buffer: Uint8Array | string, callback?: () => void): this;
  addListener(event: string, listener: (...args: any[]) => void): this;
  addListener(event: "close", listener: (hadError: boolean) => void): this;
  addListener(event: "connect", listener: () => void): this;
  addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  addListener(
    event: "connectionAttemptFailed",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  addListener(
    event: "connectionAttemptTimeout",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  addListener(event: "data", listener: (data: Buffer) => void): this;
  addListener(event: "drain", listener: () => void): this;
  addListener(event: "end", listener: () => void): this;
  addListener(event: "error", listener: (err: Error) => void): this;
  addListener(
    event: "lookup",
    listener: (err: Error, address: string, family: string | number, host: string) => void,
  ): this;
  addListener(event: "ready", listener: () => void): this;
  addListener(event: "timeout", listener: () => void): this;
  emit(event: string | symbol, ...args: any[]): boolean;
  emit(event: "close", hadError: boolean): boolean;
  emit(event: "connect"): boolean;
  emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean;
  emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean;
  emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean;
  emit(event: "data", data: Buffer): boolean;
  emit(event: "drain"): boolean;
  emit(event: "end"): boolean;
  emit(event: "error", err: Error): boolean;
  emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean;
  emit(event: "ready"): boolean;
  emit(event: "timeout"): boolean;
  on(event: string, listener: (...args: any[]) => void): this;
  on(event: "close", listener: (hadError: boolean) => void): this;
  on(event: "connect", listener: () => void): this;
  on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this;
  on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
  on(event: "data", listener: (data: Buffer) => void): this;
  on(event: "drain", listener: () => void): this;
  on(event: "end", listener: () => void): this;
  on(event: "error", listener: (err: Error) => void): this;
  on(
    event: "lookup",
    listener: (err: Error, address: string, family: string | number, host: string) => void,
  ): this;
  on(event: "ready", listener: () => void): this;
  on(event: "timeout", listener: () => void): this;
  once(event: string, listener: (...args: any[]) => void): this;
  once(event: "close", listener: (hadError: boolean) => void): this;
  once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this;
  once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
  once(event: "connect", listener: () => void): this;
  once(event: "data", listener: (data: Buffer) => void): this;
  once(event: "drain", listener: () => void): this;
  once(event: "end", listener: () => void): this;
  once(event: "error", listener: (err: Error) => void): this;
  once(
    event: "lookup",
    listener: (err: Error, address: string, family: string | number, host: string) => void,
  ): this;
  once(event: "ready", listener: () => void): this;
  once(event: "timeout", listener: () => void): this;
  prependListener(event: string, listener: (...args: any[]) => void): this;
  prependListener(event: "close", listener: (hadError: boolean) => void): this;
  prependListener(event: "connect", listener: () => void): this;
  prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  prependListener(
    event: "connectionAttemptFailed",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  prependListener(
    event: "connectionAttemptTimeout",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  prependListener(event: "data", listener: (data: Buffer) => void): this;
  prependListener(event: "drain", listener: () => void): this;
  prependListener(event: "end", listener: () => void): this;
  prependListener(event: "error", listener: (err: Error) => void): this;
  prependListener(
    event: "lookup",
    listener: (err: Error, address: string, family: string | number, host: string) => void,
  ): this;
  prependListener(event: "ready", listener: () => void): this;
  prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  prependOnceListener(event: "close", listener: (hadError: boolean) => void): this;
  prependOnceListener(event: "connect", listener: () => void): this;
  prependOnceListener(
    event: "connectionAttempt",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  prependOnceListener(
    event: "connectionAttemptFailed",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  prependOnceListener(
    event: "connectionAttemptTimeout",
    listener: (ip: string, port: number, family: number) => void,
  ): this;
  prependOnceListener(event: "data", listener: (data: Buffer) => void): this;
  prependOnceListener(event: "drain", listener: () => void): this;
  prependOnceListener(event: "end", listener: () => void): this;
  prependOnceListener(event: "error", listener: (err: Error) => void): this;
  prependOnceListener(
    event: "lookup",
    listener: (err: Error, address: string, family: string | number, host: string) => void,
  ): this;
  prependOnceListener(event: "ready", listener: () => void): this;
}

